// pages/i/order-refund.js
const BizGoodsOrderService = require('../../services/bizOrder');

Page({
  data: {
    orderId: 0,
    bizData: null,
    goodsData: null,
    tickets: []
  },

  onLoad(options) {
    this.setData({
      orderId: options.order_id
    });
  },

  onReady() {

  },

  onShow() {
    this.loadOrderDetail();
  },

  onHide() {

  },

  onUnload() {

  },

  onPullDownRefresh() {

  },

  onReachBottom() {

  },

  onShareAppMessage() {

  },

  async loadOrderDetail() {
    const orderId = this.data.orderId;
    if (!orderId) return;

    const res = await BizGoodsOrderService.getOrderDetail(orderId);
    if (res.success) {
      const tickets = res.data.tickets;
      this.setData({ bizData: res.data.biz, goodsData: res.data.goods, tickets });
    } else {
      wx.showToast({ title: res.message, icon: 'none' });
    }
  },

  async onRefundTap(e) {
    const id = e.currentTarget.dataset.id;
    if (!id) return;

    wx.showModal({
      title: '退款',
      content: '确定要发起退款申请吗？',
      success: async (res) => {
        if (res.confirm) {
          const success = await this.refundTicket(id);
          if (success) {
            wx.showToast({ title: '退款申请已提交', icon: 'success' });
            this.loadOrderDetail();
          } else {
            wx.showToast({ title: res.message, icon: 'none' });
          }
        }
      },
      fail: () => {
        wx.hideLoading();
      }
    });
  },

  async refundTicket(code) {
    const res = await BizGoodsOrderService.refundTicket(code);
    if (res.success) {
      return true;
    }
    return false;
  }
});